from datetime import timezone
from rest_framework.generics import ListCreateAPIView, ListAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from debunk.models import Spit, SpitComments
from debunk.serializers.serializers import SpitListSerializer, SpitCommentsListSerializer


#ListCreateAPIView包含get和post方法
class SpitView(ListCreateAPIView):
    '''获取吐槽列表'''
    queryset = Spit.objects.all().order_by('-create_time')

    serializer_class = SpitListSerializer


class SpitCommentsListView(ListAPIView):
    """吐槽详情页评论列表"""
    serializer_class = SpitCommentsListSerializer

    def get_queryset(self):
        # 获取当前吐槽的全部评论
        id = self.kwargs['spit_id']
        #返回数据并排序
        return SpitComments.objects.filter(spit_id=id).order_by('-create_time')

class SpitSubmitView(APIView):
    """发布吐槽"""
    def post(self, request):
        # 获取参数
        data = request.data
        author_id = data['user_id']
        # 生成时间
        time = timezone.now().strftime('%Y-%m-%d %H:%M:%S')
        # 校验成功，保存
        if len(data['content']) <= 140:
            # 将吐槽内容保存到数据库中
            spit = Spit()
            spit.author_id = author_id
            spit.create_time = time
            spit.content = data['content']
            spit.save()
            return Response({'msg': '发布成功'})
        # 校验失败
        else:
            return Response({'msg': '超过最大字符数'})